<script setup lang="ts">
const fileList: Ref<any[]> = ref([])
const file = ref<any>(undefined)
const onOversize = (file: any) => {
  console.log(file);
  showToast('文件大小不能超过 3MB');
};
const afterRead = (tmp: any) => {
  if (tmp.file.size / 1024 / 1024 > 1) {
    showToast({
      message: '您上传的图片大小大于1MB，为了您的体验，推荐您上传小于1MB的图片，但您仍可继续~',
      duration: 3000
    })
  }
  file.value = tmp
}
onMounted(function (): void {
  cFetch<User>('/account/api/userinfo',{
    auth:true,
    defaultOpts:{
      method: 'POST',
    }
  }).then((res) => {
    let config=useRuntimeConfig()
    function replaceURL(url:string):string{
      if(url===config.public.defaultUserAvatarURL)return url
      return config.public.enableReplaceImgURL?url.replace(config.public.oldImgHost,config.public.newImgHost):url
    }
    if(res.data[0].paycode)
    fileList.value.push({url:replaceURL(res.data[0].paycode),imageFit:'contain'})
  })
})
async function uploadFile() {
  if (!file.value) {
    showToast('请选择要上传的图片');
    return;
  }
  const formData = new FormData();
  formData.append('file', file.value.file)
  let newPayCodeUrl: string = ''
  await cFetch<any>(`/storage/api/upload?SESSION_TOKEN_KEY=${userStore().getToken()}`, {
    defaultOpts: {
      method: 'POST',
      body: formData
    }
  }).then((res) => {
    if (res.code === 200) {
      // showToast('上传成功')
      newPayCodeUrl = res.data[0].url
    }
  })
  await cFetch('/account/api/modify', {
    auth: true,
    defaultOpts: {
      method: 'POST',
      body: {
        paycode: newPayCodeUrl,
      }
    }
  }).then((res) => {
    if (res.code === 200) {
      showToast('修改收款码成功')
      navigateTo('/person')
    }
  })
}

onMounted(function () {
  barTitleStore().setTitle('我的收款码')
})
</script>

<template>
  <h3 style="margin-top: 1rem">点击选择收款码图片</h3>
  <van-uploader
      v-model="fileList"
      :max-size="3 * 1024 * 1024"
      @oversize="onOversize"
      reupload
      max-count="1"
      capture="camera"
      preview-size="10rem"
      style="margin: 1rem 0"
      :after-read="afterRead"
      image-fit="contain"
  />
  <van-button type="primary" @click="uploadFile">确认修改</van-button>
</template>

<style scoped>

</style>